<template>
  <div style="width: 50%; margin: 0 auto">
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="账号"
        name="email"
        :rules="[{ required: true, message: 'Please input your email!' }]"
      >
        <a-input v-model:value="formState.email">
          <template #prefix>
            <MobileOutlined class="site-form-item-icon" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <a-input-password v-model:value="formState.password">
          <template #prefix>
            <LockOutlined class="site-form-item-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item class="" :wrapper-col="{ offset: 8, span: 16 }">
        <a-flex justify="center" align="center">
          <a-button type="dashed" @click="router.push('/register')" style="margin-right: 10px"
            >注册</a-button
          >
          <a-button type="primary" html-type="submit">登录</a-button>
        </a-flex>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/http/user'
import { useUserStore } from '@/store/user'
import { UserOutlined, LockOutlined, MobileOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()

interface FormState {
  email: string
  password: string
}

const formState = reactive<FormState>({
  email: '',
  password: '',
})
const onFinish = (values: any) => {
  login(values).then((res) => {
    if (res.data.token) {
      localStorage.setItem('token', res.data.token)
      userStore.setUserInfo(res.data.userInfo)

      router.replace({ path: '/' })
    }
  })
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo)
}
</script>
